package firstG

import groovy.json.*
import twitter4j.*
import twitter4j.conf.*;

//println "twitter.groovy: params distance: " + params.get("distance") + " query is " +params.get("query")
def q = params.get("query")

def distance = params.get("distance")
if (!distance.isNumber()) distance=200
distance = distance.toInteger()

Twitter twitter = getTwitterAuth();
Query query = new Query(q);
query.setCount(100)
GeoLocation sheffield = new GeoLocation(53.377127, -1.467705);
//query.setGeoCode(sheffield, 400, Query.KILOMETERS)
query.setGeoCode(sheffield, distance, Query.KILOMETERS)
QueryResult result = twitter.search(query);

def twCount =0;
def builder = new groovy.xml.MarkupBuilder(out)

List<Status> tweets = [] 
for (;;) {
	result = twitter.search(query);
	tweets.addAll(result.getTweets())
	query = result.nextQuery()
	if (query == null) break;
}

//println "tweets size " + tweets.size()

builder.twitterData (description: "Tweets within $distance km of Sheffield for query: $q")
{
	tweets.each {
		def geo = it.getGeoLocation();

		if (geo!=null){
			def uname = it.getUser().getScreenName()
			def lat = it.getGeoLocation().getLatitude()
			def lng = it.getGeoLocation().getLongitude()
			def txt =  it.getText()
			def plc = it.getPlace()?.getFullName()
			tweet{
				screenname uname
				geoData {
					latitude lat
					longitude lng
				}
				place plc
				text txt
			}
		}
	}
}


private Twitter getTwitterAuth(){

	ConfigurationBuilder cb = new ConfigurationBuilder();
	cb.setDebugEnabled(true)
			.setOAuthConsumerKey("u59ay8TtPUn5p9VTHxdFg")
			.setOAuthConsumerSecret("LOkS2Vl9KTWXH5VMuwhb9RfIcXBXzkvyzzwD0HQtr14")
			.setOAuthAccessToken("560297710-4UmsMLOILUgIkLx6V5mdH1lbvG8ew8xvQm5YgBhY")
			.setOAuthAccessTokenSecret("mlwDtpbx9bUKTTk4wpBYVdUagGmBX6bzAYJbktoNM");
	TwitterFactory tf = new TwitterFactory(cb.build());
	Twitter twitter = tf.getInstance();

	return tf.getInstance();
}